<template>
  <div>
    <!-- show-checkbox 显示框可选 -->
    <!-- default-expand-all 默认展开子节点 -->
    <!-- check-strictly 设置父与子 默认不关联-->
    <!-- node-key="id"  用来获取和设置树形结构的节点数据 -->
    <el-tree
      ref="tree"
      v-loading="loading"
      :data="permissionList"
      :props="{label:'name'}"
      node-key="id"
      show-checkbox
      :default-expand-all="true"
      check-strictly
      style="min-height:300px"
    />
    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionListAPI } from '@/api/permission'
import { getTreeData } from '@/utils/getTreeData'
import { getRoleDetailsAPI, assignPremAPI } from '@/api/setting'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      permissionList: [],
      permIds: '',
      loading: false
    }
  },
  created() {
    this.getPermissionList()
    this.getRoleDetails()
  },
  methods: {
    // 获取当前角色的已有权限,进行数据回填（获取角色详情）
    async getRoleDetails() {
      this.loading = true
      const res = await getRoleDetailsAPI(this.roleId)
      // console.log(res)
      // setCheckedKeys()  给树形结构赋值
      this.$refs.tree.setCheckedKeys(res.data.permIds)
      this.loading = false
    },
    //   获取所有权限
    async getPermissionList() {
      const res = await getPermissionListAPI()
      //   console.log(res)
      this.permissionList = getTreeData(res.data)
    },
    // 取消按钮
    cancelButton() {
      this.$emit('closeEvent')
    },

    // 点击确定，给角色分配权限
    async setRolesBtn() {
      const res = await assignPremAPI({ id: this.roleId, permIds: this.$refs.tree.getCheckedKeys() })
      // console.log(res)
      this.$message.success(res.message)
      this.$emit('closeEvent')
    },
    // 点击树形节点，获取当前的值
    handleNodeClick(val) {

    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
